/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ReadingFrm.java
 *
 * Created on 2011-11-8, 14:06:53
 */
package com.edu.kamai.client;

import com.edu.kamai.client.control.scoreControl;
import com.edu.kamai.config.Constant;
import com.edu.kamai.utility.TimeFormat;
import com.edu.kamai.xml.beans.choiceXML;
import com.edu.kamai.xml.beans.reading.readingQuestion;
import com.edu.kamai.xml.beans.reading.readingXML;
import com.edu.kamai.xmlparser.reading.reading;
import com.edu.kamai.xmlparser.reading.readingPaperParser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Scanner;
import javax.swing.Timer;

/**
 *
 * @author xyzhu
 */
public class ReadingFrm extends javax.swing.JFrame {

    /** Creates new form ReadingFrm */
    public ReadingFrm(ContestFrm cf,String sn,String pp,int pid,int cID) {
        contestFrm = cf;
        sutdentName = sn;
        paperPath = pp;
        paperID = pid;
        contestID = cID;
        initComponents();
        initPaper();
        initAnswerPaper();
        initQuestion(questionIndex);
        exeTime = 0;
        B_Submit.setEnabled(false);
        setNet();
        readingTimer = new Timer(1000, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                exeTime++;
                TF_ReadingTime.setText(TimeFormat.retTimeFormatting(exeTime));
                
                if(exeTime >= timeLimit){
                    if(nextReading() == 0){
                        sumbitPaper();
                    }
                }
                
            }
        });
        
        readingTimer.start();
    }
    
    private void setNet(){
        try{
            InputStream in = getClass().getResourceAsStream(Constant.netiniFilePath);
            Scanner scan = new Scanner(in);
            List<String> netList = new ArrayList<String>();
            
            while(scan.hasNextLine()){
                String line = scan.nextLine();
                if(!line.equals("")){
                    if(!line.startsWith("#")){
                        netList.add(line);
                    }
                }
            }
            scoreControl.setNetList(netList);
            scan.close();
            in.close();
        }catch(Exception ex){
            ex.printStackTrace();
            //Control.setNetList(new ArrayList<String>());
        }
        scoreControl.setServer();
    }
    
    private void showMessage(int ans,String msg){
        if(ans == 1){
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Done", ans);
        }else{
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Error", ans);
        }
    }
    
    
    private void initPaper(){
        rpp = new readingPaperParser(paperPath);
        rXml = rpp.parseSpeakingXML();
        totalQuestionCnt = rXml.getReadingquestionList().size();
        questionIndex = 0;
        
    }
    
    private void initAnswerPaper(){
        studentAnswer = new Hashtable<Integer, String>();
        paperKey = new Hashtable<Integer, String>();
    }
    
    
    private void initQuestion(int index){
        readingQuestion rq = rXml.getReadingquestionList().get(index);
        TA_Main.setText(rq.getMainTxt());
        cXml = rq.getChoices();
        choiceIndex = 0;
        initChoice(choiceIndex);
        timeLimit = rq.getTimeLimit();
        TF_LimitTime.setText(TimeFormat.retTimeFormatting(timeLimit));
        clearChoiceAnswer();
    }
    
    private void initChoice(int index){
        
        // run to the end
        if(questionIndex == totalQuestionCnt-1 && index == cXml.size() - 1){
            B_Submit.setEnabled(true);
        }
        
        choiceXML tmp = cXml.get(choiceIndex);
        TF_ChoiceTxt.setText(tmp.getMainTxt());
        TF_ATXT.setText(tmp.getChoicesTxt().get(0));
        TF_BTXT.setText(tmp.getChoicesTxt().get(1));
        TF_CTXT.setText(tmp.getChoicesTxt().get(2));
        TF_DTXT.setText(tmp.getChoicesTxt().get(3));
        paperKey.put(questionIndex * 4 + index, tmp.getKeys());
        
        if(studentAnswer.get(questionIndex * 4 + index) != null){
            SetChoice(studentAnswer.get(questionIndex * 4 + index));
        }else{
            clearChoiceAnswer();
        }
    }
    
    private String getChoice(){
        if (RB_A.isSelected() == true){
            return "a";
        }else if (RB_B.isSelected() == true){
            return "b";
        }else if (RB_C.isSelected() == true){
            return "c";
        }else if (RB_D.isSelected() == true){
            return "d";
        }
        return "";
    }
    
    private void clearChoiceAnswer(){
        buttonGroup1.clearSelection();
    }
    
    private void SetChoice(String s){
        if(s.equalsIgnoreCase("a")){
            RB_A.setSelected(true);
        }else if(s.equalsIgnoreCase("b")){
            RB_B.setSelected(true);
        }else if (s.equalsIgnoreCase("c")) {
            RB_C.setSelected(true);
        }else if(s.equalsIgnoreCase("d")){
            RB_D.setSelected(true);
        }else{
            clearChoiceAnswer();
        }
    }
    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        TA_Main = new javax.swing.JTextArea();
        RB_A = new javax.swing.JRadioButton();
        RB_B = new javax.swing.JRadioButton();
        RB_C = new javax.swing.JRadioButton();
        RB_D = new javax.swing.JRadioButton();
        TF_ATXT = new javax.swing.JTextField();
        TF_BTXT = new javax.swing.JTextField();
        TF_CTXT = new javax.swing.JTextField();
        TF_DTXT = new javax.swing.JTextField();
        B_NextC = new javax.swing.JButton();
        B_NextR = new javax.swing.JButton();
        B_Submit = new javax.swing.JButton();
        TF_ReadingTime = new javax.swing.JTextField();
        TF_LimitTime = new javax.swing.JTextField();
        B_PrevC = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        TF_ChoiceTxt = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        TA_Main.setColumns(20);
        TA_Main.setEditable(false);
        TA_Main.setLineWrap(true);
        TA_Main.setRows(5);
        jScrollPane1.setViewportView(TA_Main);

        buttonGroup1.add(RB_A);
        RB_A.setText("A");

        buttonGroup1.add(RB_B);
        RB_B.setText("B");

        buttonGroup1.add(RB_C);
        RB_C.setText("C");

        buttonGroup1.add(RB_D);
        RB_D.setText("D");

        TF_ATXT.setEditable(false);

        TF_BTXT.setEditable(false);

        TF_CTXT.setEditable(false);

        TF_DTXT.setEditable(false);

        B_NextC.setText("next choice");
        B_NextC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_NextCActionPerformed(evt);
            }
        });

        B_NextR.setText("next reading");
        B_NextR.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_NextRActionPerformed(evt);
            }
        });

        B_Submit.setText("submit");
        B_Submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_SubmitActionPerformed(evt);
            }
        });

        TF_ReadingTime.setEditable(false);

        TF_LimitTime.setEditable(false);

        B_PrevC.setText("prev choice");
        B_PrevC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_PrevCActionPerformed(evt);
            }
        });

        TF_ChoiceTxt.setColumns(20);
        TF_ChoiceTxt.setEditable(false);
        TF_ChoiceTxt.setLineWrap(true);
        TF_ChoiceTxt.setRows(5);
        jScrollPane2.setViewportView(TF_ChoiceTxt);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(RB_D)
                            .addComponent(RB_C)
                            .addComponent(RB_A)
                            .addComponent(RB_B))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(TF_CTXT, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
                            .addComponent(TF_BTXT, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
                            .addComponent(TF_ATXT, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
                            .addComponent(TF_DTXT, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(B_PrevC, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                            .addComponent(B_NextC, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                            .addComponent(B_NextR, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(B_Submit, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(TF_ReadingTime)
                    .addComponent(TF_LimitTime, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(TF_LimitTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(TF_ReadingTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(119, 119, 119)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(39, 39, 39)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(TF_ATXT, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(RB_A))
                                .addGap(18, 18, 18))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(B_PrevC)
                                .addGap(14, 14, 14)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(TF_BTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(RB_B))
                            .addComponent(B_NextC))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(TF_CTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(RB_C)
                            .addComponent(B_NextR))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(TF_DTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(RB_D)
                            .addComponent(B_Submit)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(309, 309, 309)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void B_NextCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_NextCActionPerformed
        // TODO add your handling code here:
        studentAnswer.put(questionIndex * 4 + choiceIndex, getChoice());
        if(choiceIndex + 1>= cXml.size()){
            showMessage(0, "no next choice");
            return;
        }
        choiceIndex = choiceIndex + 1;
        initChoice(choiceIndex);
        
    }//GEN-LAST:event_B_NextCActionPerformed

    private void judgePaper(){
        readingTimer.stop();
        reading ra = new reading(paperKey, studentAnswer);
        List<Integer> res = ra.check();
        int numOfErr = res.size();
        
        int score = Constant.readingTotalScore - 
                numOfErr * Constant.readingSingleScore;
        
        showMessage(1, "numOfErr:" + numOfErr);
        
        /*
        int ans = scoreControl.updateScoreByContestIDAndStudentID(
                contestID, sutdentName, score, (int)exeTime, 
                Constant.READING_PAPER_ID);
        showMessage(ans, scoreControl.getMessage());
         * *
         */
        
    }
    
    private void sumbitPaper(){
        studentAnswer.put(questionIndex * 4 + choiceIndex, getChoice());
        judgePaper();
        this.setVisible(false);
        contestFrm.setVisible(true);
    }
    
    private void B_SubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_SubmitActionPerformed
        // TODO add your handling code here:
        sumbitPaper();
    }//GEN-LAST:event_B_SubmitActionPerformed

    private int nextReading(){
        studentAnswer.put(questionIndex * 4 + choiceIndex, getChoice());
        if(questionIndex + 1 >= totalQuestionCnt){
            showMessage(0, "no next reading");
            return 0;
        }
        questionIndex = questionIndex + 1;
        initQuestion(questionIndex);
        return 1;
    }
    
    private void B_NextRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_NextRActionPerformed
        // TODO add your handling code here:
        nextReading();
    }//GEN-LAST:event_B_NextRActionPerformed

    private void B_PrevCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_PrevCActionPerformed
        // TODO add your handling code here:
        studentAnswer.put(questionIndex * 4 + choiceIndex, getChoice());
        if(choiceIndex - 1< 0){
            showMessage(0, "no prev choice");
            return;
        }
        choiceIndex = choiceIndex - 1;
        initChoice(choiceIndex);
    }//GEN-LAST:event_B_PrevCActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                String filename = "C:\\Users\\user\\Documents\\NetBeansProjects\\"
                + "trunk\\kamai_edu\\build\\web\\UpLoad\\Paper\\"
                + "f95cee52b884358d4b8bef49a5ec2508.xml";
                new ReadingFrm(null, null, filename, 0, 0).setVisible(true);
            }
        });
    }
    
    private final Timer readingTimer;
    private long exeTime;
    private long timeLimit;
    
    private ContestFrm contestFrm;
    private String sutdentName;
    private String paperPath;
    
    private int paperID;
    private int contestID;
    private int totalQuestionCnt;
    private int questionIndex;
    private int choiceIndex;
    
    
    private readingPaperParser rpp;
    private readingXML rXml;
    private List<choiceXML> cXml;
    
    private Hashtable<Integer,String> studentAnswer;
    private Hashtable<Integer,String> paperKey;
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton B_NextC;
    private javax.swing.JButton B_NextR;
    private javax.swing.JButton B_PrevC;
    private javax.swing.JButton B_Submit;
    private javax.swing.JRadioButton RB_A;
    private javax.swing.JRadioButton RB_B;
    private javax.swing.JRadioButton RB_C;
    private javax.swing.JRadioButton RB_D;
    private javax.swing.JTextArea TA_Main;
    private javax.swing.JTextField TF_ATXT;
    private javax.swing.JTextField TF_BTXT;
    private javax.swing.JTextField TF_CTXT;
    private javax.swing.JTextArea TF_ChoiceTxt;
    private javax.swing.JTextField TF_DTXT;
    private javax.swing.JTextField TF_LimitTime;
    private javax.swing.JTextField TF_ReadingTime;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
